package com.example.springclouduserserver.controller;


import com.example.springclouduserserver.config.PassToken;
import com.example.springclouduserserver.entity.User;
import com.example.springclouduserserver.exception.NeedToLogin;
import com.example.springclouduserserver.response.JsonResult;
import com.example.springclouduserserver.response.StatusCode;
import com.example.springclouduserserver.service.MailService;
import com.example.springclouduserserver.service.UserService;
import com.example.springclouduserserver.util.JwtUtils;
import com.example.springclouduserserver.util.UserLogin;
import com.example.springclouduserserver.util.UserRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
@ResponseBody
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ExceptionHandler
    @ResponseBody
    public JsonResult allExceptionHandler(Exception e){
        System.out.println("================进入异常处理================");
        return new JsonResult(StatusCode.PARAMS_ERROR.getCode(),e.getMessage(),"","");
    }

    @PassToken
    @GetMapping("/test")
    public String Usertest(){return "User test serve";}

    @GetMapping("/getUser")
    public User getUser(@RequestParam("id") int id){

        return userService.queryUserById(id);
    }


    @GetMapping("/getUserByUsername")
    public User getUserByUsername(@RequestParam("username") String username){
        return userService.queryUserByUsername(username);
    }


    @PassToken
    @GetMapping("getCheckCode")
    public JsonResult getCheckCode(@RequestParam("email") String email){
        log.info("进入方法getCheckCode");
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的注册验证码为："+checkCode;
        //向redis里存入数据和设置缓存时间
        try{
            redisTemplate.opsForValue().set(email, checkCode, 60 * 3, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }
        //info(redisTemplate.opsForValue().get(email).toString());
        try {
            mailService.sendSimpleMail(email, "注册验证码", message);

        }catch (Exception e){
            return new JsonResult(StatusCode.EXCEPTION.getCode(),StatusCode.EXCEPTION.getMessage(),e, "");
        }
        return new JsonResult(StatusCode.SUCCESS.getCode(),StatusCode.SUCCESS.getMessage(),checkCode, "");

    }

    @PassToken
    @PostMapping("/userRegister")
    public JsonResult userRegister(@RequestBody User user){
        String[] saltAndCiphertext = UserRegister.encryptPassword(user.getPassword());
        user.setSalt(saltAndCiphertext[0]);
        user.setPassword(saltAndCiphertext[1]);

        if(Objects.equals(redisTemplate.opsForValue().get(user.getEmail()), user.getCheckCode())){
            userService.addUser(user);
            return new JsonResult(StatusCode.SUCCESS.getCode(),StatusCode.SUCCESS.getMessage(),"", "");
        }
        else{
            return new JsonResult(StatusCode.PARAMS_ERROR.getCode(),StatusCode.PARAMS_ERROR.getMessage(),"验证码错误", "");
        }

    }


    @PassToken
    @PostMapping("/userLogin")
    public JsonResult userLogin(@RequestBody User user){
        try{
            user.setPassword(UserLogin.getInputPasswordCiph(user.getPassword(), userService.queryUserByUsername(user.getUsername()).getSalt()));
        }catch (NullPointerException e){
            log.info("账户不存在");
        };
        switch (UserLogin.userLogin(user)){
            case 200:
                User account=userService.queryUserByUsername(user.getUsername());
                String jwtToken = JwtUtils.createToken(String.valueOf(account.getId()),account.getRealname(),account.getUsername());
                return new JsonResult(StatusCode.SUCCESS.getCode(),StatusCode.SUCCESS.getMessage(),"", jwtToken);
            case 410:
                return new JsonResult(StatusCode.NOT_SUPPORTED.getCode(),StatusCode.NOT_SUPPORTED.getMessage(),"", "");
            case 444:
                return new JsonResult(StatusCode.INVALID_AUTHCODE.getCode(),StatusCode.INVALID_AUTHCODE.getMessage(),"", "");
            default:
                return new JsonResult(StatusCode.UNKNOWN_ERROR.getCode(),StatusCode.UNKNOWN_ERROR.getMessage(),"","");
        }
    }




}
